package com.alibaba.dubbo.remoting.msgcodec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

import com.alibaba.dubbo.remoting.MessageDecode;

public class GZipDecode implements MessageDecode {
	private static final int BUFFER = 8*1024;
	 
	@Override
	public int decode(InputStream in, OutputStream out/*, MessageEncodeRegistry registry*/) throws IOException {
			int ch = in.read();
		int count;
		if(ch == 0){
			byte data[] = new byte[BUFFER];
			int n = 0;
			while ((count = in.read(data, 0, BUFFER)) != -1) {
				out.write(data, 0, count);
				n += count;
			}
			return n;
		}else if(ch == 1){
			GZIPInputStream gis = new GZIPInputStream(in);
			//ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte data[] = new byte[BUFFER];
			int n = 0;
			while ((count = gis.read(data, 0, BUFFER)) != -1) {
				out.write(data, 0, count);
				n += count;
			}
	
			gis.close();
			out.flush();
			
			//byte [] os = baos.toByteArray();
			//out.write(os);
			//out.flush();
			/*
			if(registry != null){
				registry.appendEncode("gzip");
			}
			*/
			//return os.length;
			return n;
		}else{
			InflaterInputStream gis = new InflaterInputStream(in);
			//ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte data[] = new byte[BUFFER];
			int n = 0;
			while ((count = gis.read(data, 0, BUFFER)) != -1) {
				out.write(data, 0, count);
				n += count;
			}
	
			gis.close();
			
			//byte [] os = baos.toByteArray();
			//out.write(os);
			//out.flush();
			/*
			if(registry != null){
				registry.appendEncode("gzip");
			}
			*/
			//return os.length;
			return n;
		}
	}
}
